package com.ruoyi.cms.utils;

import com.alibaba.fastjson.JSON;
import com.ruoyi.cms.domain.ArticleDraft;
import com.ruoyi.cms.domain.response.ToutiaoArticleRspDTO;
import com.ruoyi.cms.enums.PlatformEnum;
import com.ruoyi.common.utils.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.HashMap;

/**
 * 网页爬虫工具
 *
 * @author Lorry
 * @since 2020-04-19 17:02
 **/
@Component
public class CrawlerUtil {
//    @Autowired
//    private QiNiuCloudService qiNiuCloudService;

    /**
     * 爬取文章
     *
     * @param url
     * @param platform
     * @return
     * @throws Exception
     */
    public ArticleDraft crawlerDraftArticle(String url, PlatformEnum platform) throws Exception {
        ArticleDraft draft = new ArticleDraft();
        String title="";

        switch (platform) {
            /*case WX:
                Document doc = Jsoup.parse(new URL(url), 5000);
                String original = doc.select("#copyright_logo").html();
                //非原创
                if (!StringUtils.equals(original, "原创")) {
                    draft.setOriginal(0);
//                    return draft;
                } else {
                    draft.setOriginal(1);
                }
                //过滤包含音频的文章
                Elements videoIframe = doc.select("iframe.video_iframe");
                if (CollectionUtils.isNotEmpty(videoIframe)) {
                    draft.setResult(2);
                    return draft;
                }
                //过滤包含视频的文章
                Elements audioIframe = doc.select("mpvoice.audio_iframe");
                if (CollectionUtils.isNotEmpty(audioIframe)) {
                    draft.setResult(2);
                    return draft;
                }

                Elements jsContent = doc.select("#js_content");
                String content = jsContent.html();
                String author = doc.select("meta[name=author]").attr("content");
                String description = doc.select("meta[name=description]").attr("content");
                String title = doc.select("meta[property=og:title]").attr("content");
                String coverImage = doc.select("meta[property=og:image]").attr("content");
                String suffix = StringUtils.getParam(coverImage, "wx_fmt");
                if (StringUtils.isEmpty(suffix)) {
                    suffix = "jpg";
                }
                String coverImgName = UUIDGenerator.getUUID().concat(".").concat(suffix);
                String newCoverImgUrl = qiNiuCloudService.uploadWithUrl(coverImage, coverImgName);

                draft.setAuthor(author);
                draft.setDescription(description);
                draft.setTitle(title);
                draft.setCoverImage(newCoverImgUrl);

                //图片转存到服务器
                *//*Elements imgElements = jsContent.select("img");
                HashMap<String, String> map = new HashMap<>(8);
                for (Element image : imgElements) {
                    String dataSrc = image.attr("data-src");
                    if (StringUtils.isEmpty(dataSrc)) {
                        continue;
                    }
                    suffix = StringUtils.getParam(dataSrc, "wx_fmt");
                    if (StringUtils.isEmpty(suffix)) {
                        IMG_SUFFIX = suffix;
                    }
                    String filename = UUIDGenerator.getUUID().concat(".").concat(IMG_SUFFIX);
                    String imgUrl = qiNiuCloudService.uploadWithUrl(dataSrc, filename);
//                    String imgUrl = QiNiuCloudUtil.uploadWithUrl(dataSrc, filename);
                    map.put(dataSrc, imgUrl);
                }

                for (Map.Entry<String, String> entry : map.entrySet()) {
                    content = content.replace(entry.getKey(), entry.getValue());
                }
                draft.setContent(content.replace("data-src", "src"));*//*
                draft.setContent(content);
                break;*/
            case TT:
                String json = JsoupUtil.get4TtJson(url);
                ToutiaoArticleRspDTO articleRspDTO = JSON.parseObject(json, ToutiaoArticleRspDTO.class);
                if (articleRspDTO.getStatus() == 0) {
                    ToutiaoArticleRspDTO.DataBean article = articleRspDTO.getData();
                    if (StringUtils.isNotEmpty(article.getTitle())) {
                        draft.setContent(article.getContent());
                        title = article.getTitle();
                        if (title.length() > 50) {
                            title = title.substring(0, 50).concat("...");
                        }
                        draft.setTitle(title);
                        draft.setUrl(url);
                    }
                }

                break;
            default:
//                log.error("不支持的抓取类型");
                System.err.println("不支持的抓取类型");
        }

        return draft;
    }

    public static void main(String[] args) throws Exception {
        String html = getHtml3("https://mp.weixin.qq.com/s?__biz=MjM5MjAxNDM4MA==&mid=2666309924&idx=1&sn" +
                "=6f800e369eb989a881968a1ab3cb631d&chksm" +
                "=bdb4c0678ac34971db8408243f7c3e240297a115fd2d208f05d132cd7eafabd71490726fb419&scene=0&xtrack=1#rd");
//        HtmlUtil.saveToFile(html, "包含视频的文章.html");

//        String url = "https://mp.weixin.qq.com/s?__biz=MzA4ODY4ODUzNQ==&mid=2663458705&idx=1&sn" +
//                "=73d8549adb089eca5a810459825fe688&chksm
//                =8b13d569bc645c7f3435c8ed117dacb5f578f30abe27ebc958cdf31130dbf843e6cb3c01774a&scene=126&sessionid
//                =1587571452&key=79d4e23884d837c854ba845d484bd83332c54fe37d1a1c081b34b74dfb64c87549db77455ceca288f1c2b6929ea658e5d5448a6579b0b210c19e14bfc7bdb7939d72edb219ece4e7c2ebfcf6b77a2c0c&ascene=1&uin=MzA4NjUxMTU%3D&devicetype=Windows+10+x64&version=62090069&lang=zh_CN&exportkey=AwRyIGPVOADbwUtAxxK6xe4%3D&pass_ticket=Q6W%2FWdFcrkyFoFDURzUVbZ1f7eCXKvN8ogYbNiDGuc8%3D";
//        CrawlerUtil crawlerUtil = new CrawlerUtil();
//        ArticleDraft draft = crawlerUtil.crawlerWxArticle(url, PlatformEnum.WX);
//        System.out.println(JSON.toJSONString(draft));
    }

    public static String getHtml3(String requestUrl) throws Exception {
        Document doc = Jsoup.parse(new URL(requestUrl), 5000);
        Elements jsContent = doc.select("#js_content");
        String html = jsContent.html();

        Elements elements = doc.select("img");
        HashMap<String, String> map = new HashMap<>(32);
        String path = null;
        for (Element elements1 : elements) {
            String dataSrc = elements1.attr("data-src");
            System.out.println(dataSrc);
        }
        return html;
    }
}
